package com.vue.admin.util;

import org.apache.ibatis.exceptions.TooManyResultsException;

import java.sql.SQLException;
/**
 * 增删改时返回前端的判断实体
 * @author Lihhz 2017-03-15
 *
 */
public class ResponseState {
	/**错误信息*/
	protected String message;
	 /**错误编码*/
	protected short code;
	 /**是否成功*/
	protected boolean success;
	 /**返回数据*/
	protected Object data;

	public ResponseState() {
		this.code = 0;
		this.success = true;
		this.data = null;
	}
	public ResponseState(Object data) {
		this.code = 0;
		this.success = true;
		this.data = data;
	}

	public ResponseState(String message) {
		this.message = message;
	}

	public ResponseState(short code, String message) {
		this.code = code;
		this.message = message;
	}

	public ResponseState(boolean success, String message) {
		this.success = success;
		this.message = message;
	}

	public ResponseState(short code, boolean success, String message) {
		this.code = code;
		this.success = success;
		this.message = message;
	}

	public ResponseState(Exception ex) {
		this.code = -1;
		this.success = false;
		if (ex.getMessage() == null) {
			this.message = "参数不正确或不完整";
		} else if (ex.getCause() instanceof SQLException)
			this.message = "服务器异常：执行数据库语句错误";
		else if(ex.getCause() instanceof TooManyResultsException)
			this.message = "应该查询出一条结果,但查询出多条结果.";
		else
			setMessage(ex.getMessage());
	}

	public String getMessage() {
		return this.message;
	}

	public void setMessage(String message) {
		if (message != null)
			message = message.replace("\"", "'").replace('\r', '\0');
		this.message = message;
	}

	public short getCode() {
		return this.code;
	}

	public void setCode(short code) {
		this.code = code;
	}

	public boolean getSuccess() {
		return this.success;
	}

	public void setSuccess(boolean success) {
		this.success = success;
	}

	public Object getData() {
		return this.data;
	}

	public void setData(Object data) {
		this.data = data;
	}

	public String toString() {
		StringBuffer sbJson = new StringBuffer("{\"code\":");
		sbJson.append(this.code).append(",\"message\":\"").append(this.message)
				.append("\",").append("\"success\":").append(this.success)
				.append("}");
		return sbJson.toString();
	}
}